'''
apb: android play back.
@author: Stone.J

play back commands file:
TOUCH|{'x':434,'y':544,'type':'downAndUp',}
TOUCH|{'x':382,'y':1160,'type':'downAndUp',}
TOUCH|{'x':456,'y':736,'type':'downAndUp',}
TOUCH|{'x':164,'y':648,'type':'downAndUp',}
TOUCH|{'x':209,'y':845,'type':'downAndUp',}
ASSERT|{'keys':'a b c d e z',}
'''

try:
    from com.android.monkeyrunner import MonkeyRunner as mr
except ImportError:
    pass

class MrDummyDevice:
    def touch(self, x=None, y=None, type=None):
        print 'touch %s %s %s' % (x, y, type)

    def shell(self, shell):
        return 'a b c d e f g'

def mr_assert(dev, keys):
    view = dev.shell('uiautomator dump /dev/tty')
    for k in keys.split():
        if not k in view:
            return False
    return True


MR_CMDS = {
    'TOUCH':    lambda dev, args: dev.touch(**args),
    'DRAG':     lambda dev, args: dev.drag(**args),
    'PRESS':    lambda dev, args: dev.press(**args),
    'TYPE':     lambda dev, args: dev.type(**args),
    'WAIT':     lambda dev, args: mr.sleep(**args),
    'ASSERT':   lambda dev, args: mr_assert(dev, **args),
    }

def mr_play_back(dev, cmds):
    cmds = [cmds] if isinstance(cmds, str) else cmds
    for cmd in cmds:
        c, args = cmd.split('|')
        try:
            args = eval(args)
        except:
            print 'unable to parse args'
            continue

        if c not in MR_CMDS:
            print 'unknown command: ' + cmd
            continue

        ret = MR_CMDS[c](dev, args)

        #TODO how to handle when assert failed.
        if('ASSERT' == c and not ret):
            print 'ASSERT FAIL.'
            break


if __name__ == '__main__':
    dev = MrDummyDevice()
    mr_play_back(dev, open('/Users/stone/Tmp/a'))
    mr_play_back(dev, "TOUCH|{'x':10000,'y':10000,'type':'downAndUp',}")
